package ru.elteam.web.beans.request;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import ru.elteam.ejb.logic.UserMangementBean;
import ru.elteam.web.beans.session.UserBean;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

/**
 * Created with IntelliJ IDEA.
 * User: Nikita.Brazhnikov
 * Date: 10/1/12
 * Time: 12:22 PM
 * To change this template use File | Settings | File Templates.
 */
@Named("user_reg")
@RequestScoped
public class UserRegistrationBean {

	private static final Logger log = Logger.getLogger(UserRegistrationBean.class);

	@Inject
	private UserBean users;

	@EJB
	private UserMangementBean userman;

	private String username;
	private String password;
	private String email;
	private String infoMessage;
	private Integer id;
	private boolean success = true;

	public static final String REG_SUCCESS_VIEW = "reg_summary";


	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getInfoMessage() {
		return infoMessage;
	}

	public boolean isSuccess() {
		return success;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String register() {
		if (StringUtils.isEmpty(username)) {
			appendInfo("User name is empty");
			success = false;
		}
		if (StringUtils.isEmpty(password)) {
			appendInfo("Password is empty");
			success = false;
		}
		if (StringUtils.isEmpty(email)) {
			appendInfo("Email is empty");
			success = false;
		}
		if (success) {
			users.setEmail(email);
			users.setUsername(username);
			saveNewUser();
			log.trace("Going to the registration success page");
			return REG_SUCCESS_VIEW;
		}
		log.trace("Wrong user's data, back to registration page");
		return "";
	}

	private void saveNewUser() {
		id = userman.register(username, password, email);
	}

	private void appendInfo(String newInfoPart) {
		if (infoMessage == null)
			infoMessage = "";
		if (!infoMessage.endsWith(" ")) {
			infoMessage = infoMessage + " ";
		}
		infoMessage = infoMessage + newInfoPart;
	}
}
